<?php
/**********************************************************************
 *                                                                    *    
 * Copyright (c) 2009 Dmytro Bezhnar. All rights reserved.  			      *
 *                                                                    *
 **********************************************************************/

/**
 * Memcache persistable object.
 *
 * @version $Id: MemcacheManager.php,v 1.4 2008/03/20 13:33:51 master Exp $
 */

class MemcacheManager {
	
	/**
     * Memcache connection
     * @var Memcache
     */
    private $memcache = null;
    
    private $available = true;
    
	function __construct()
    {
    	global $options, $memcache;
    	
    	if (!is_object($memcache))
    	{
    		$memcache = new Memcache; 
    		$memcache->connect($options['memcache']['host'], $options['memcache']['port']) or $this->available = false;
    		$this->memcache_log = $options['memcache']['log'];
    		if (!$this->available) {
	    		func_log('ERROR: connect to '.$options['memcache']['host'].', port='.$options['memcache']['port'],LOG_ERR);
	    	}
    	}
    	$this->memcache=$memcache;
    }
    
	/**
	 * Set Object to Memcached
	 * 
	 * @param string $name  key name
	 * @param mixed  $value content
	 * @param int    $time  time to live
	 * @param int    $use_compression
	 */    
    function set($name,$value,$use_compression=false,$time)
    {
    	if ($this->memcache_log) {
	    	func_log('set - '.$name.', time='.$time,'memcache',LOG_ERR);
    		func_log(print_r($value,true),'memcache',LOG_ERR);
    	}
    	$this->memcache->set($name,$value,$use_compression,$time);
    }
	
    /**
     * Get Object from Memcached
     * 
     * @param string $name key name
     */
    function get($name)
    {
    	$data = $this->memcache->get($name);
    	if ($data !== false)
    	{
    		if ($this->memcache_log)
    		{
    			func_log('get - '.$name,'memcache',LOG_ERR);
    			func_log(print_r($data,true),'memcache',LOG_ERR);
    		}
    	}
    	return $data; 
    }
    
    function is_available() {
    	return $this->available;
    }
}
?>